﻿using OrderStateMachineWebApi.Models;
using OrderStateMachineWebApi.Services;

namespace OrderStateMachineWebApi.ServicesImpl
{

    public class InMemoryOrderRepository : IOrderRepository
    {
        private readonly Dictionary<Guid, Order> _orders = new Dictionary<Guid, Order>();
        private readonly object _lock = new object();

        public Task<Order> CreateOrderAsync(decimal amount)
        {
            lock (_lock)
            {
                var order = new Order
                {
                    Amount = amount,
                    Notes = string.Empty
                };

                _orders.Add(order.Id, order);
                return Task.FromResult(order);
            }
        }

        public Task<Order> GetOrderByIdAsync(Guid id)
        {
            lock (_lock)
            {
                _orders.TryGetValue(id, out var order);
                return Task.FromResult(order);
            }
        }

        public Task<List<Order>> GetAllOrdersAsync()
        {
            lock (_lock)
            {
                return Task.FromResult(_orders.Values.ToList());
            }
        }

        public Task UpdateOrderAsync(Order order)
        {
            lock (_lock)
            {
                if (_orders.ContainsKey(order.Id))
                {
                    _orders[order.Id] = order;
                }
                return Task.CompletedTask;
            }
        }
    }

}
